#!/usr/bin/python
# -*- coding:utf-8 -*-
from Ui_video import *
import cv2
from PyQt5 import QtCore, QtGui, QtWidgets
import os
import sys
import time
import socket
BUFSIZE = 1024
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP协议
light_info = 2


class MainWindow(QtWidgets.QMainWindow, Ui_mainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.initUI()
        self.open_wl_light()
        self.close_wl_light()

    def initUI(self):
        self.open_pushButton.clicked.connect(self.start)

    def start(self):
        s1 = self.lineEdit_2.text()
        s3 = "http://" + s1 + "/?action=stream"

        self.timerCamera = QtCore.QTimer(self)
        self.cap = cv2.VideoCapture(s3)
        self.timerCamera.timeout.connect(self.showPic)
        self.timerCamera.start(10)

    def showPic(self):
        success, video_label = self.cap.read()
        if success:
            show = cv2.cvtColor(video_label, cv2.COLOR_BGR2RGB)
            showImage = QtGui.QImage(
                show.data, show.shape[1], show.shape[0], QtGui.QImage.Format_RGB888)
            self.video_label.setPixmap(QtGui.QPixmap.fromImage(showImage))
            self.timerCamera.start(10)

    def open_wl_light(self):
        self.open_wl_pushButton.clicked.connect(self.lightsignalopen)

    def close_wl_light(self):
        self.close_wl_pushButton.clicked.connect(self.lightsignalclose)

    def lightsignalopen(self):
        light_info = int("01")
        msg = "%02d".strip() % (light_info)
        ip_port = ("192.168.1.7", 8888)
        client.sendto(msg.encode('utf-8'), ip_port)

    def lightsignalclose(self):
        light_info = int("10")
        msg = "%02d".strip() % (light_info)
        ip_port = ("192.168.1.7", 8888)
        client.sendto(msg.encode('utf-8'), ip_port)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())
    client.close()
